package com.yanx.framework.advice;

import com.yanx.common.exception.BaseException;
import com.yanx.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 系统异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public BaseException handler(Exception e) {
        BaseException be = new BusinessException(e);
        this.logException(be);
        return be;
    }

//    /**
//     * 业务异常
//     *
//     * @param e
//     * @return
//     */
//    @ExceptionHandler(BaseException.class)
//    @ResponseBody
//    public <E extends BaseException> BaseException baseExceptionHandler(E e) {
//        this.logException(e);
//        return handler(e);
//    }

    /**
     * 打印异常信息
     *
     * @param be
     */
    private void logException(BaseException be) {
        Throwable cause = be.getCause();
        if (cause == null) {
            cause = be;
        }
        log.error("E{} : {} -> {}\n{}", be.getCode(), be.getMessage(), cause.getClass().getName(), getThrowMsg(cause));
    }

    private String getThrowMsg(Throwable cause) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < cause.getStackTrace().length; i++) {
            String str = cause.getStackTrace()[i].toString();
            //只显示前20行
            if (i < 20) {
                sb.append(str).append("\r\n");
            } else {
                break;
            }
        }
        return sb.toString();
    }
}
